package com.truckdispatching.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.truckdispatching.R;
import com.truckdispatching.UserManager;
import com.truckdispatching.http.controller.LogoutHttpController;
import com.truckdispatching.http.controller.ReportTruckLocationHttpController;
import com.truckdispatching.http.controller.UpdateAgentPeopleHttpController;
import com.truckdispatching.http.controller.UpdateTruckStatusHttpController;
import com.truckdispatching.http.util.OnResponseHandler;
import com.truckdispatching.http.util.OnResponseListener;
import com.truckdispatching.map.BaiduMapManager;
import com.truckdispatching.upgrade.UpgradeManager;
import com.truckdispatching.util.SharedPreferencesUtil;

public class MainActivity extends BaseActivity implements OnClickListener {
	private MapView mMapView = null;
	private MapController mMapController = null;
	private MKMapViewListener mMapListener = null;
	// 定位相关
	private LocationClient mLocClient;
	private MyLocationListenner mLocationListener = new MyLocationListenner();
	private LocationData locData = null;
	private MyLocationOverlay myLocationOverlay = null;

	private TextView mTitle;
	private ImageView mHomepageButton;
	private ImageView mPhoneCallButton;
	private ImageView mSettingButton;
	private View mModifyUserInfoButton;
	private View mModifyPasswordButton;
	private View mNotificationButton;
	private View mUpdateButton;
	private TextView mIntermediaryButton;
	private View mExitButton;

	private View mMapViewLayout;
	private View mSettingViewLayout;

	private Button mTruckStateSwitch;

	private UpdateTruckStatusHttpController mUpdateTruckStatusHttpController;

	private Drawable markerDrawable;

	private Handler mReportLocationHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		SharedPreferencesUtil.getInstance().initWithApplication(getApplication());
		UpgradeManager.getInstance().checkVersion(true, this);
		mTitle = (TextView) findViewById(R.id.tv_title);
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapController = mMapView.getController();
		mMapView.setLongClickable(true);

		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(mLocationListener);

		mReportLocationHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (locData.latitude != 0 || locData.longitude != 0) {
					mController = new ReportTruckLocationHttpController();
					mController.sendRequest(locData.latitude, locData.longitude);
					mReportLocationHandler.sendEmptyMessageDelayed(1, 30 * 60 * 1000);
				} else {
					mReportLocationHandler.sendEmptyMessageDelayed(1, 10 * 1000);
				}
			}
		};

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(10000);// 设置发起定位请求的间隔时间为5000ms
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setPoiNumber(5); // 最多返回POI个数
		option.setPoiDistance(1000); // poi查询距离
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		mLocClient.setLocOption(option);
		mLocClient.start();
		mMapView.getController().setZoom(14);
		mMapView.getController().enableClick(true);

		mMapView.setBuiltInZoomControls(true);
		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null) {
					title = mapPoiInfo.strText;
					showToast(title);
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub

			}
		};
		mMapView.regMapViewListener(BaiduMapManager.getInstance().mBMapManager, mMapListener);
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
		myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();

		markerDrawable = this.getResources().getDrawable(R.drawable.icon_marka);
		ov = new OverlayTest(markerDrawable, mMapView);
		mMapView.getOverlays().add(ov);

		mHomepageButton = (ImageView) findViewById(R.id.btn_homepage);
		mHomepageButton.setOnClickListener(this);
		mPhoneCallButton = (ImageView) findViewById(R.id.btn_phonecall);
		mPhoneCallButton.setOnClickListener(this);
		mSettingButton = (ImageView) findViewById(R.id.btn_setting);
		mSettingButton.setOnClickListener(this);

		mModifyUserInfoButton = findViewById(R.id.btn_modify_userinfo);
		mModifyUserInfoButton.setOnClickListener(this);
		mModifyPasswordButton = findViewById(R.id.btn_modify_password);
		mModifyPasswordButton.setOnClickListener(this);
		mNotificationButton = findViewById(R.id.btn_notification);
		mNotificationButton.setOnClickListener(this);
		mUpdateButton = findViewById(R.id.btn_update);
		mUpdateButton.setOnClickListener(this);
		mIntermediaryButton = (TextView) findViewById(R.id.btn_intermediary);
		if (UserManager.getAgent() != null && !UserManager.getAgent().equals("")) {
			mIntermediaryButton.setEnabled(false);
			mIntermediaryButton.setText("经办人手机号:" + UserManager.getAgent());
		} else {
			mIntermediaryButton.setEnabled(true);
			mIntermediaryButton.setText("经办人手机号");
		}
		mIntermediaryButton.setOnClickListener(this);
		mExitButton = findViewById(R.id.btn_exit);
		mExitButton.setOnClickListener(this);
		mTruckStateSwitch = (Button) findViewById(R.id.truck_switch);
		mTruckStateSwitch.setOnClickListener(this);
		if (UserManager.isTruckStatus()) {
			mTruckStateSwitch.setBackgroundResource(R.drawable.switch_empty);
		} else {
			mTruckStateSwitch.setBackgroundResource(R.drawable.switch_full);
		}

		mMapViewLayout = findViewById(R.id.map_layout);
		mSettingViewLayout = findViewById(R.id.setting_layout);
		mSettingViewLayout.setVisibility(View.GONE);
		requestNewLocation();
		mReportLocationHandler.sendEmptyMessage(1);
	}

	private void sendUpdateTruckStatusReqeust(boolean status) {
		if (mUpdateTruckStatusHttpController != null) {
			mUpdateTruckStatusHttpController.cancelHttpRequest();
		} else {
			mUpdateTruckStatusHttpController = new UpdateTruckStatusHttpController();
		}
		mUpdateTruckStatusHttpController.setOnResponseListener(new OnResponseListener() {

			@Override
			public void onResponseError(int errorCode, String errorMessage) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onResponse(Object response) {

			}
		});
		mUpdateTruckStatusHttpController.sendRequest(String.valueOf(!status));
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		//		if (mLocClient != null)
		//			mLocClient.stop();
		//		mMapView.destroy();
		//		BaiduMapManager.getInstance().destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	/**
	 * 重新定位
	 */
	public void requestNewLocation() {
		mLocClient.requestLocation();
	}

	private ReportTruckLocationHttpController mController;
	OverlayTest ov = null;

	private String mCurrentLocation = "";

	/**
	 * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		//		private int count = 10000;

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			//			count++;
			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			myLocationOverlay.setData(locData);
			mCurrentLocation = location.getAddrStr();

			OverlayItem item = new OverlayItem(new GeoPoint((int) (locData.latitude * 1E6), (int) (locData.longitude * 1E6)), "item", "item");
			item.setMarker(markerDrawable);
			ov.removeAll();
			ov.addItem(item);
			ov.showLocation();

			mMapView.refresh();
			mMapController.animateTo(new GeoPoint((int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6)),
				null);
			//			if (count >= 6 * 30) {
			//				mController = new ReportTruckLocationHttpController();
			//				mController.sendRequest(locData.latitude, locData.longitude);
			//				count = 0;
			//			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.truck_switch:
			String msg = "是否确定修改为";
			final boolean status = UserManager.isTruckStatus();
			if (status) {
				msg = msg + "满载状态？";
			} else {
				msg = msg + "空车状态";
			}
			new AlertDialog.Builder(this).setTitle("提示").setMessage(msg).setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (!status) {
						mTruckStateSwitch.setBackgroundResource(R.drawable.switch_empty);
					} else {
						mTruckStateSwitch.setBackgroundResource(R.drawable.switch_full);
					}
					UserManager.setTruckStatus(!status);
					sendUpdateTruckStatusReqeust(!status);
					requestNewLocation();
				}
			}).setNegativeButton("取消", null).show();
			break;
		case R.id.btn_homepage:
			if (mMapViewLayout.getVisibility() != View.VISIBLE) {
				mTitle.setText("560调度宝");
				mHomepageButton.setImageResource(R.drawable.main_homepage_checked);
				mSettingButton.setImageResource(R.drawable.main_setting_normal);
				mMapViewLayout.setVisibility(View.VISIBLE);
				mSettingViewLayout.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_setting:
			if (mSettingViewLayout.getVisibility() != View.VISIBLE) {
				mTitle.setText("设置");
				mHomepageButton.setImageResource(R.drawable.main_homepage_normal);
				mSettingButton.setImageResource(R.drawable.main_setting_checked);
				mSettingViewLayout.setVisibility(View.VISIBLE);
				mMapViewLayout.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_phonecall:
			new AlertDialog.Builder(this).setTitle("提示").setMessage("确定拨打560免费客服电话吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Uri callUri = Uri.parse("tel:4000566560");
						Intent i = new Intent(Intent.ACTION_CALL, callUri);
						startActivity(i);
					}
				}).setNegativeButton("取消", null).show();
			break;
		case R.id.btn_modify_userinfo: {
			Intent intent = new Intent(this, ModifyUserInfoActivity.class);
			startActivity(intent);
			break;
		}
		case R.id.btn_modify_password: {
			Intent intent = new Intent(this, ModifyPasswordAcivity.class);
			startActivity(intent);
			break;
		}
		case R.id.btn_notification: {
			Intent intent = new Intent(this, NotificationAcivity.class);
			startActivity(intent);
			break;
		}
		case R.id.btn_update:
			UpgradeManager.getInstance().checkVersion(false, this);
			break;
		case R.id.btn_intermediary:
			final EditText input = new EditText(this);
			input.setInputType(InputType.TYPE_CLASS_NUMBER);
			input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(11) });
			new AlertDialog.Builder(this).setTitle("请输入推荐人手机号").setView(input)
				.setPositiveButton("保存", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						final String mobile = input.getText().toString();
						if (checkPhoneNumber(mobile)) {
							new AlertDialog.Builder(MainActivity.this).setMessage(
								"您输入的手机经办人号码为\r\n" + mobile + "\r\n注意，提交后无法修改")
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										UpdateAgentPeopleHttpController controller = new UpdateAgentPeopleHttpController();
										controller.setOnResponseListener(new OnResponseHandler() {

											@Override
											public void onResponseError(int errorCode, String errorMessage) {
												dismissLoadingDialog();
												if (errorMessage != null && !errorMessage.equals("")) {
													showToast("修改失败：" + errorMessage);
												} else {
													showToast("修改失败");
												}
											}

											@Override
											public void onResponse(Object response) {
												dismissLoadingDialog();
												UserManager.setAgent(mobile);
												if (mobile != null && !mobile.equals("")) {
													mIntermediaryButton.setEnabled(false);
													mIntermediaryButton.setText("经办人手机号:" + mobile);
												} else {
													mIntermediaryButton.setEnabled(true);
													mIntermediaryButton.setText("经办人手机号");
												}
												showToast("修改成功");
											}
										});
										controller.sendRequest(mobile);
										showLoadingDialog();
									}
								}).setNegativeButton("取消", null).show();
						}
					}
				}).setNegativeButton("取消", null).show();
			break;
		case R.id.btn_exit:
			UserManager.logout();
			new LogoutHttpController().sendRequest();
			Intent intent = new Intent(this, LoginActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			break;
		default:
			break;
		}

	}

	private boolean checkPhoneNumber(String phonenumber) {
		if (phonenumber.equals("")) {
			showToast("请输入手机号");
			return false;
		}
		if (phonenumber.length() != 11) {
			showToast("手机号格式错误");
			return false;
		}
		if (!phonenumber.startsWith("1")) {
			showToast("手机号格式错误");
			return false;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		moveTaskToBack(true);
	}

	class OverlayTest extends ItemizedOverlay<OverlayItem> {

		private TextView locationText;
		private Handler mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				mMapView.removeView(locationText);
			};
		};

		public OverlayTest(Drawable marker, MapView mapView) {
			super(marker, mapView);
			locationText = new TextView(MainActivity.this);
			locationText.setMaxWidth(380);
			locationText.setTextSize(20);
			locationText.setGravity(Gravity.CENTER);
			locationText.setBackgroundResource(R.drawable.toast_frame);
		}

		protected boolean onTap(int index) {
			showLocation();
			return true;
		}

		public boolean onTap(GeoPoint pt, MapView mapView) {
			mHandler.removeMessages(1);
			mMapView.removeView(locationText);
			super.onTap(pt, mapView);
			return false;
		}

		public void showLocation() {
			mMapView.removeView(locationText);
			locationText.setText(mCurrentLocation);
			GeoPoint gp = getItem(0).getPoint();
			MapView.LayoutParams layoutParam = new MapView.LayoutParams(
				// 控件宽,继承自ViewGroup.LayoutParams
				MapView.LayoutParams.WRAP_CONTENT,
				// 控件高,继承自ViewGroup.LayoutParams
				MapView.LayoutParams.WRAP_CONTENT,
				// 使控件固定在某个地理位置
				gp,
				// 控件对齐方式
				MapView.LayoutParams.BOTTOM_CENTER);
			// 添加View到MapView中
			mMapView.addView(locationText, layoutParam);
			mHandler.removeMessages(1);
			mHandler.sendEmptyMessageDelayed(1, 5000);
		}
	}
}
